package com.czh.hander.security;

import com.alibaba.fastjson.JSON;
import com.czh.domain.ResponseResult;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//认证失败处理类
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
//        authException.printStackTrace();
        ResponseResult<Object> result;
        //通过异常类型判断出现的问题
        if (authException instanceof BadCredentialsException) {
            //用户名或密码错误
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), authException.getMessage());
        } else if (authException instanceof InsufficientAuthenticationException) {
            //需要登录
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else {
            //无权限操作
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}